package meijuli.com.join51.business.network;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;

import meijuli.com.join51.business.app.MApplication;

import me.foji.anko.ContextKt;

/**
 * 网络工具类
 *
 * @author Wizong 2017-05-19 13:09
 */
public class NetworkUtil {

    /**
     * 获取网络连接类型
     *
     * @return 网络连接类型
     */
    public static NetworkMonitor.NetworkType networkType() {
        ConnectivityManager manager = ContextKt.connectivityManager(MApplication.Companion.get());
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo == null) {
            return NetworkMonitor.NetworkType.UNKNOWN;
        }

        NetworkMonitor.NetworkType networkType = NetworkMonitor.NetworkType.UNKNOWN;
        switch (networkInfo.getType()) {
            case ConnectivityManager.TYPE_WIFI:
                networkType = NetworkMonitor.NetworkType.WIFI;
                break;
            case ConnectivityManager.TYPE_MOBILE:
                int subtype = networkInfo.getSubtype();
                @SuppressLint("ServiceCast")
                TelephonyManager telephonyManager = (TelephonyManager) MApplication.Companion.get()
                        .getSystemService(Context.TELECOM_SERVICE);
                switch (subtype) {
                    case TelephonyManager.NETWORK_TYPE_LTE:
                        if (!telephonyManager.isNetworkRoaming()) {
                            networkType = NetworkMonitor.NetworkType._4G;
                        }
                        break;

                    case TelephonyManager.NETWORK_TYPE_UMTS:
                    case TelephonyManager.NETWORK_TYPE_HSDPA:
                    case TelephonyManager.NETWORK_TYPE_EVDO_0:
                        if (!telephonyManager.isNetworkRoaming()) {
                            networkType = NetworkMonitor.NetworkType._3G;
                        }
                        break;

                    case TelephonyManager.NETWORK_TYPE_GPRS:
                    case TelephonyManager.NETWORK_TYPE_EDGE:
                    case TelephonyManager.NETWORK_TYPE_CDMA:
                        if (!telephonyManager.isNetworkRoaming()) {
                            networkType = NetworkMonitor.NetworkType._2G;
                        }
                        break;
                        default: {

                        }
                }
                break;
                default: {

                }
        }
        return networkType;
    }

    /**
     * 获取网络是否连接
     *
     * @return true 连接 false 未连接
     */
    public static boolean isConnected() {
        ConnectivityManager manager = ContextKt.connectivityManager(MApplication.Companion.get());
        return manager.getActiveNetworkInfo() != null;
    }
}
